package cn.hchaojie.ssm.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hchaojie.ssm.domain.Post;
import cn.hchaojie.ssm.service.PostService;

/**
 * 页面渲染，分两种：一种是服务器渲染，一种是客户端渲染
 * @author hchaojie
 *
 */
@Controller
public class RestPostController {
	@Autowired
	PostService service;
	/**
	 * 查询文章列表
	 */
	@RequestMapping(path = "/posts", method = RequestMethod.GET)
	@ResponseBody
	public List<Post> list() {
		return service.findAll();
	}
	
	/** 根据文章id查询文章信息 */
	@RequestMapping(path = "/posts/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Post getById(@PathVariable("id") int id) {
		return service.getById(id);
	}
	
	/** 根据文章id查询文章信息 */
	@RequestMapping(path = "/posts/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public Map<String, Object> deleteById(@PathVariable("id") int id) {
		service.deleteById(id);
		
		Map<String, Object> result = new HashMap<>();
		result.put("code", 1);
		result.put("success", true);
		result.put("message", "删除成功！");

		return result;
	}
	
	@RequestMapping(path = "/posts/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public Map<String, Object> update(@PathVariable("id") int id, Post p) {
		service.update(id, p);
		
		Map<String, Object> result = new HashMap<>();
		result.put("code", 1);
		result.put("success", true);
		result.put("message", "删除成功！");

		return result;
	}
	
	@RequestMapping("/posts/ajax")
	public String ajax() {
		return "ajax";
	}
}
